package com.gitee.wsl.common.ui.theme.palette.colorspace.ansi

/**
 * 生成ANSI格式的编码输出
 *
 * @author Phillip Webb
 * @since 1.0.0
 */
object AnsiEncoder {
    private val ENCODE_JOIN = ";"
    private val ENCODE_START = "\u001b["
    private val ENCODE_END = "m"
    private val RESET = "0;" + AnsiColor.DEFAULT

    /**
     * 创建ANSI字符串，参数中的[AnsiElement]会被转换为编码形式。
     *
     * @param elements 节点数组
     * @return ANSI字符串
     */
    fun encode(vararg element: AnsiElement): String {
        val elements:Array<out AnsiElement> = element
        val sb = StringBuilder()
        buildEnabled(sb, elements)
        return sb.toString()
    }

    /**
     * 追加需要需转义的节点
     *
     * @param sb       [StringBuilder]
     * @param elements 节点列表
     */
    private fun buildEnabled(sb: StringBuilder, elements: Array<out AnsiElement>) {
        var writingAnsi = false
        var containsEncoding = false
        for (element in elements) {
            if (element is AnsiElement) {
                containsEncoding = true
                if (writingAnsi) {
                    sb.append(ENCODE_JOIN)
                } else {
                    sb.append(ENCODE_START)
                    writingAnsi = true
                }
            } else {
                if (writingAnsi) {
                    sb.append(ENCODE_END)
                    writingAnsi = false
                }
            }
            sb.append(element)
        }

        // 恢复默认
        if (containsEncoding) {
            sb.append(if (writingAnsi) ENCODE_JOIN else ENCODE_START)
            sb.append(RESET)
            sb.append(ENCODE_END)
        }
    }
}
